from enum import Enum

import mutagen
import logging
import base64


class AudioMetaKey(Enum):
    """枚举对应的标签名 0 ID3  1 FLAC 2 MP4"""
    TITLE = ["TIT2", "TITLE", "\xa9nam"]
    ARTIST = ["TPE1", "ARTIST", "\xa9ART"]
    ALBUM = ["TALB", "ALBUM", "\xa9alb"]
    TRACKNUMBER = ["TRCK", "TRACKNUMBER", "trkn"]
    YEAR = ["TYER", "DATE", "\xa9day"]
    LYRICS = ["USLT::XXX", "LYRICS", "\xa9lyr"]
    PICTURE = ["APIC:", "", "covr"]


class AudioMediaMeta:
    filepath: str
    holder: any

    def __init__(self, filepath):
        self.filepath = filepath
        self.holder = mutagen.File(filepath)

    def get_tag(self, key: AudioMetaKey):
        """获取音乐文件元数据"""
        try:
            if isinstance(self.holder.tags, mutagen._vorbis.VComment) or isinstance(self.holder, mutagen.ogg.OggFileType):
                # OGG
                if key is AudioMetaKey.PICTURE:
                    return base64.b64encode(self.holder.pictures[0].data)
                return self.holder[key.value[1]][0]
            elif isinstance(self.holder.tags, mutagen.id3.ID3) or isinstance(self.holder, mutagen.id3.ID3FileType):
                # ID3
                if key is AudioMetaKey.LYRICS:
                    return self.holder.tags[key.value[0]].text
                elif key is AudioMetaKey.PICTURE:
                    return base64.b64encode(self.holder.tags[key.value[0]].data)
                return self.holder.tags[key.value[0]].text[0]
            elif isinstance(self.holder.tags, mutagen.mp4.MP4Tags):
                # MP4
                if key is AudioMetaKey.PICTURE:
                    return base64.b64encode(self.holder.tags[key.value[2]][0])
                if key is AudioMetaKey.TRACKNUMBER:
                    return self.holder.tags[key.value[2]][0][0]
                else:
                    return self.holder.tags[key.value[2]][0]
        except Exception as err:
            logging.debug(f"标签{err}不存在")
        return None

    def get_bitrate(self):
        """获取比特率"""
        return self.holder.info.bitrate

    def get_frame_rate(self):
        """获取采样率"""
        return self.holder.info.sample_rate
